const path = require('path')
const iconv = require("iconv-lite")
const glob = require('glob')
const rm = require('rimraf')
const srcPath = path.resolve(__dirname, './dist')
const staticPath = path.resolve(__dirname, './public/static')
const spawn = require('child_process').spawn
const pages = glob.sync('./src/pages/*/main.js');

function buildProject (i) {
  let filepath = pages[i];

  if (!filepath) {
    console.log('\x1B[32m%s\x1B[0m', '编译完成')
    return
  }

  let fileList = filepath.split('/');
  let fileName = fileList[fileList.length - 2];
  console.log('\x1B[34m%s\x1B[0m', '================================================================================')
  console.log('\x1B[32m%s\x1B[0m', '开始编译目录' + fileName + '...')
  let processObj = spawn("npm", ["run", "build-single", fileName])

  // 监听执行命令输出内容事件
  processObj.stdout.on("data", function(thunk) {
    console.log('\x1B[32m%s\x1B[0m', iconv.decode(thunk, "utf-8"))
  })

  processObj.stderr.on("data", function(data) {
    console.log('\x1B[33m%s\x1B[0m', iconv.decode(data, "utf-8"))
  })

  processObj.on("close", function(code) {
    console.log("close: ", code);

    if (code == 0) {
      console.log(fileName + '编译完成')
      i++
      buildProject(i)
    }
  })

  processObj.on("exit", function(code) {
    console.log("exit: ", code);
  })
}

rm(srcPath, err => {
  // 迁移static
  console.log('\x1B[32m%s\x1B[0m', '迁移static')
  spawn("mkdir", [srcPath])
  spawn("cp", ["-r", staticPath, srcPath])
  
  if (err) throw err
  buildProject(0)
})
